import time
import threading
import queue
from utils.audio_utils import AudioAlert


class AlertSystem:
    def __init__(self, min_interval: float = 3.0):
        self.audio = AudioAlert()
        self.q = queue.Queue()
        self.thread = None
        self.running = False
        self.min_interval = min_interval
        self.last_ts = 0.0

    def start(self):
        if self.thread and self.thread.is_alive():
            return
        self.running = True
        self.thread = threading.Thread(target=self._loop, daemon=True)
        self.thread.start()

    def stop(self):
        self.running = False
        try:
            if self.thread:
                self.thread.join(timeout=1.0)
        except Exception:
            pass

    def enqueue(self, status: str):
        # status: left | right | center | lost
        try:
            self.q.put_nowait(status)
        except Exception:
            pass

    def _speak_for(self, status: str):
        if status == 'left':
            self.audio.speak('向左偏离，请回到车道中间')
        elif status == 'right':
            self.audio.speak('向右偏离，请回到车道中间')
        elif status == 'lost':
            self.audio.speak('未检测到道路，请减速注意')
        else:
            # center 或其他状态不提示，轻微蜂鸣可选
            pass

    def _loop(self):
        while self.running:
            try:
                status = self.q.get(timeout=0.2)
            except queue.Empty:
                continue
            now = time.time()
            if now - self.last_ts >= self.min_interval:
                self._speak_for(status)
                self.last_ts = now